package org.jsola.hr.core;

import org.apache.ibatis.session.SqlSessionFactory;
import org.jsola.autoconfigure.orm.mybatis.MybatisConfigurationSupport;
import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import tk.mybatis.spring.annotation.MapperScan;

import javax.sql.DataSource;

import static org.jsola.hr.constant.HrConstants.SQL_SESSION_FACTORY_BEAN_NAME;
import static org.jsola.hr.constant.HrConstants.TX;

/**
 * @author zhr
 */
@Configuration
@EnableConfigurationProperties(HrProperties.class)
@MapperScan(basePackages = "org.jsola.hr.dao", sqlSessionFactoryRef = SQL_SESSION_FACTORY_BEAN_NAME)
@AutoConfigureBefore(MybatisAutoConfiguration.class)
public class HrAutoConfiguration {

    @Bean(name = SQL_SESSION_FACTORY_BEAN_NAME)
    @ConditionalOnMissingBean(name = SQL_SESSION_FACTORY_BEAN_NAME)
//    @Primary
    public SqlSessionFactory hrSqlSessionFactory(DataSource datasource, MybatisConfigurationSupport mybatisConfigurationSupport) throws Exception {
        return mybatisConfigurationSupport.build(datasource);
    }

    @Bean(name = TX)
    @ConditionalOnMissingBean(name = TX)
//    @Primary
    public DataSourceTransactionManager hrTx(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }


}
